package com.hsgene.user.controller.organization;

import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.basic.SimpleStringUtils;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.OrderHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.user.condition.CompanyCondition;
import com.hsgene.user.domain.Company;
import com.hsgene.user.dto.orginazation.CompanyDto;
import com.hsgene.user.dto.orginazation.CompanyIdsDto;
import com.hsgene.user.exception.OrganizationErrorCode;
import com.hsgene.user.service.CompanyService;
import com.hsgene.user.service.DepartmentService;
import com.hsgene.user.service.PositionService;
import com.hsgene.user.service.api.GeneratorService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 公司管理类
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.order.controller.organization
 * @author: maodi
 * @createDate: 2018/11/5 10:02
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/companies")
public class CompanyController {

    private static Logger LOGGER = LogManager.getLogger(CompanyController.class);

    @Resource
    CompanyService companyService;

    @Resource
    DepartmentService departmentService;

    @Resource
    PositionService positionService;

    @Resource
    GeneratorService generatorService;

    /**
     * @param companyName 公司名称
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 公司插入去重
     * @author maodi
     * @createDate 2018/11/13 16:46
     */
    @GetMapping("insert/repeat")
    public ApiResult<NullObject> insertRepeat(@RequestParam("companyName") String companyName) {
        try {
            if (StringUtils.isBlank(companyName)) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_ID_IS_NOT_NULL);
            }
            int count = companyService.queryCompanyCountByName(companyName);
            if (count > 0) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_NAME_IS_EXIST);
            }
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.INSERT_COMPANY_REPEAT_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.INSERT_COMPANY_REPEAT_IS_ERROR);
        }
    }

    /**
     * @param companyName 公司名称
     * @param companyId   公司id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 公司修改去重
     * @author maodi
     * @createDate 2018/11/13 16:46
     */
    @GetMapping("update/repeat")
    public ApiResult<NullObject> updateRepeat(@RequestParam("companyName") String companyName, @RequestParam
            ("companyId") String companyId) {
        try {
            if (StringUtils.isBlank(companyId)) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_ID_IS_NOT_NULL);
            }
            if (StringUtils.isBlank(companyName)) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_ID_IS_NOT_NULL);
            }
            int count = companyService.queryCompanyCountByNameExcludeSelf(companyName, companyId);
            if (count > 0) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_NAME_IS_EXIST);
            }
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.UPDATE_COMPANY_REPEAT_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.UPDATE_COMPANY_REPEAT_IS_ERROR);
        }
    }

    /**
     * @param companyId 公司id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.user.domain.Company>
     * @description 根据公司id获取公司信息
     * @author maodi
     * @createDate 2018/11/13 16:59
     */
    @GetMapping("{company_id}")
    public ApiResult<Company> getCompanyByCompanyId(@PathVariable("company_id") String companyId) {
        try {
            List<Company> list = companyService.queryCompanyById(companyId);
            if (list != null && list.size() > 0) {
                return ApiResult.succ(list.get(0));
            } else {
                return ApiResult.succ(null, "暂无数据");
            }
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.QUERY_COMPANY_BY_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.QUERY_COMPANY_BY_ID_IS_ERROR);
        }
    }


    /**
     * @param
     * @return com.hsgene.common.util.result.ApiResult<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
     * @description 查询公司下拉框数据源
     * @author maodi
     * @createDate 2018/11/7 9:21
     */
    @GetMapping("select")
    public ApiResult<List<Map<String, Object>>> select() {
        try {
            return ApiResult.succ(companyService.selectCompany());
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.SELECT_COMPANY_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.SELECT_COMPANY_IS_ERROR);
        }
    }

    /**
     * @param page        页数
     * @param size        每页数量
     * @param companyName 公司名称
     * @param sort        修改时间排序规则
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.support.Pagination<com.hsgene.user
     * .domain.Company>>
     * @description 查询公司信息/公司列表
     * @author maodi
     * @createDate 2018/11/6 17:40
     */
    @GetMapping
    public ApiResult<Pagination<CompanyDto>> queryCompany(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size,
            @RequestParam(name = "companyName", required = false) String companyName,
            @RequestParam(name = "sort", required = false, defaultValue = "desc") String sort) {
        try {
            if (page == null) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(page.toString())) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NOT_POSITIVE_INTEGER);
            }
            if (size == null) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(size.toString())) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NOT_POSITIVE_INTEGER);
            }
            sort = sort.toLowerCase();
            if (!"desc".equalsIgnoreCase(sort) && !"asc".equalsIgnoreCase(sort)) {
                return ApiResult.fail(CommonErrorCode.SORT_ORDER_IS_ERROR);
            }
            CompanyCondition condition = new CompanyCondition();
            condition.setCompanyName(companyName);
            LimitHelper limitHelper = LimitHelper.create(page, size);
            condition.setLimitHelper(limitHelper);
            OrderHelper orderHelper = OrderHelper.create("gtoc.update_date_time", sort);
            condition.setOrderHelper(orderHelper);
            List<CompanyDto> result = companyService.queryCompanyByCondition(condition);
            addNum(result, page, size);
            int totalCount = companyService.queryCompanyCountByCondition(condition);
            Pagination pagination = Pagination.newInstance(limitHelper, totalCount, result);
            return ApiResult.succ(pagination);
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.QUERY_COMPANY_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.QUERY_COMPANY_IS_ERROR);
        }
    }

    /**
     * @param company 公司
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 新增公司
     * @author maodi
     * @createDate 2018/11/6 17:50
     */
    @PostMapping
    public ApiResult<NullObject> insertCompany(@RequestBody Company company) {
        try {
            String companyName = company.getCompanyName();
            if (StringUtils.isBlank(companyName)) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_NAME_IS_NOT_NULL);
            }
            int count = companyService.queryCompanyCountByName(companyName);
            if (count > 0) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_NAME_IS_EXIST);
            }
            String id = generatorService.getGenerator("", "").getData().getSerialNumber();
            company.setId(id);
            Date date = new Date();
            company.setCreateDateTime(date);
            company.setUpdateDateTime(date);
            int returnCount = companyService.insertCompany(company);
            if (returnCount != 1) {
                return ApiResult.fail(OrganizationErrorCode.INSERT_COMPANY_IS_ERROR);
            }
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.INSERT_COMPANY_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.INSERT_COMPANY_IS_ERROR);
        }
    }

    /**
     * @param company 公司
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 修改公司信息
     * @author maodi
     * @createDate 2018/11/6 18:14
     */
    @PutMapping("{company_id}")
    public ApiResult<NullObject> updateCompany(@PathVariable("company_id") String companyId, @RequestBody Company
            company) {
        try {
            if (StringUtils.isBlank(companyId)) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_ID_IS_NOT_NULL);
            }
            company.setId(companyId);
            String companyName = company.getCompanyName();
            int count = companyService.queryCompanyCountByNameExcludeSelf(companyName, companyId);
            if (count > 0) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_NAME_IS_EXIST);
            }
            company.setUpdateDateTime(new Date());
            int queryCount = companyService.queryCompanyById(companyId).size();
            if (queryCount < 1) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_IS_NOT_EXIST);
            }
            int returnCount = companyService.updateCompany(company);
            if (returnCount < 1) {
                return ApiResult.fail(OrganizationErrorCode.UPDATE_COMPANY_IS_ERROR);
            } else if (returnCount > 1) {
                return ApiResult.succ(null, OrganizationErrorCode.COMPANY_IS_MULTI.getDescription());
            } else {
                return ApiResult.succ();
            }
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.UPDATE_COMPANY_IS_ERROR, e);
            return ApiResult.fail(OrganizationErrorCode.UPDATE_COMPANY_IS_ERROR);
        }
    }

    /**
     * @param companyId 公司id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 删除公司信息
     * @author maodi
     * @createDate 2018/11/6 18:18
     */
    @DeleteMapping("{company_id}")
    public ApiResult<NullObject> deleteCompany(@PathVariable("company_id") String companyId) {
        try {
            if (StringUtils.isBlank(companyId)) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_ID_IS_NOT_NULL);
            }
            int queryCount = companyService.queryCompanyById(companyId).size();
            if (queryCount < 1) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_HAVE_BEEN_DELETED);
            }
            int usedCount = departmentService.queryCountByCompanyId(companyId);
            usedCount += positionService.queryCountByCompanyId(companyId);
            if (usedCount > 0) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_IS_USED_CAN_NOT_DELETE);
            }
            Company company = new Company();
            company.setId(companyId);
            company.setUpdateDateTime(new Date());
            int returnCount = companyService.deleteCompany(company);
            if (returnCount < 1) {
                return ApiResult.fail(OrganizationErrorCode.DELETE_COMPANY_IS_ERROR);
            } else if (returnCount > 1) {
                return ApiResult.succ(null, OrganizationErrorCode.COMPANY_IS_MULTI.getDescription());
            } else {
                return ApiResult.succ();
            }
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.DELETE_COMPANY_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.DELETE_COMPANY_IS_ERROR);
        }
    }

    /**
     * @param companyIdsDto 公司id数组字符串实体
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 公司批量删除
     * @author maodi
     * @createDate 2018/11/13 17:18
     */
    @DeleteMapping
    public ApiResult<NullObject> deleteCompanyMulti(@RequestBody CompanyIdsDto companyIdsDto) {
        try {
            String companyIdsStr = companyIdsDto.getCompanyIds();
            if (StringUtils.isBlank(companyIdsStr)) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_IDS_IS_NOT_NULL);
            }
            String[] companyIds = companyIdsStr.split(",");
            if (companyIds == null || companyIds.length < 1) {
                return ApiResult.fail(OrganizationErrorCode.COMPANY_IDS_IS_NOT_NULL);
            }
            companyService.deleteCompanyMulti(companyIds);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrganizationErrorCode.DELETE_COMPANY_MULTI_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrganizationErrorCode.DELETE_COMPANY_MULTI_IS_ERROR);
        }
    }

    /**
     * @param list 公司列表
     * @param page 页数
     * @param size 每页数量
     * @return void
     * @description 为公司列表添加序号
     * @author maodi
     * @createDate 2018/11/8 10:30
     */
    private void addNum(List<CompanyDto> list, int page, int size) {
        int start = (page - 1) * size + 1;
        for (CompanyDto companyDto : list) {
            companyDto.setNum(start++);
        }
    }

}
